package com.news.servlet.admin;

import com.news.model.News;
import com.news.model.Sort;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/newsEdit")
public class NewsEditServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取新闻ID
            int newsId = Integer.parseInt(request.getParameter("id"));
            
            // 获取新闻详情
            News news = newsService.getNewsById(newsId);
            if (news == null) {
                throw new Exception("新闻不存在");
            }
            
            // 获取分类列表
            List<Sort> sortList = newsService.getAllSorts();
            
            // 设置属性
            request.setAttribute("news", news);
            request.setAttribute("sortList", sortList);
            
            // 转发到编辑页面
            request.getRequestDispatcher("/admin/news_edit.jsp").forward(request, response);
        } catch (Exception e) {
            request.getSession().setAttribute("message", "获取新闻失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/newsManage");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        News news = null;
        try {
            // 检查是否是多部分请求
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new ServletException("表单必须包含文件上传字段");
            }

            // 创建文件上传处理器
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            // 解析请求
            List<FileItem> items = upload.parseRequest(request);
            
            // 创建新闻对象
            news = new News();
            String imagePath = null;
            boolean removeImage = false;
            
            // 处理表单字段
            for (FileItem item : items) {
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String value = item.getString("UTF-8");
                    
                    switch (fieldName) {
                        case "new_id":
                            news.setNew_id(Integer.parseInt(value));
                            break;
                        case "title":
                            news.setTitle(value);
                            break;
                        case "sort_id":
                            news.setSort_id(Integer.parseInt(value));
                            break;
                        case "content":
                            news.setContent(value);
                            break;
                        case "removeImage":
                            removeImage = "true".equals(value);
                            break;
                    }
                } else {
                    // 处理文件上传
                    if (item.getSize() > 0) {
                        String fileName = System.currentTimeMillis() + "_" + 
                            item.getName().substring(item.getName().lastIndexOf("/") + 1);
                        String uploadPath = getServletContext().getRealPath("/images");
                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        File file = new File(uploadPath, fileName);
                        item.write(file);
                        imagePath = fileName;
                    }
                }
            }
            
            // 获取原新闻信息
            News oldNews = newsService.getNewsById(news.getNew_id());
            news.setWriter(oldNews.getWriter());
            news.setNewTime(oldNews.getNewTime());
            
            // 更新新闻
            if (newsService.updateNews(news, imagePath, removeImage)) {
                request.getSession().setAttribute("message", "新闻更新成功！");
                response.sendRedirect(request.getContextPath() + "/admin/newsManage");
            } else {
                request.getSession().setAttribute("message", "新闻更新失败！");
                response.sendRedirect(request.getContextPath() + "/admin/newsEdit?id=" + news.getNew_id());
            }
        } catch (Exception e) {
            request.getSession().setAttribute("message", "新闻更新失败：" + e.getMessage());
            String redirectUrl = request.getContextPath() + "/admin/newsEdit?id=";
            if (news != null) {
                redirectUrl += news.getNew_id();
            } else {
                redirectUrl += request.getParameter("new_id");
            }
            response.sendRedirect(redirectUrl);
        }
    }
} 